package upload

import (
	"github.com/gin-gonic/gin"
	"higame/modules/log"
	"higame/modules/utils"
	"net/http"
	"path"
)

func html(ctx *gin.Context) {
	file, err := ctx.FormFile("file")
	if err != nil {
		log.Error.Println(err)
		ctx.JSON(http.StatusPreconditionFailed, gin.H{
			"code": http.StatusPreconditionFailed,
			"msg":  "获取文件出错!",
			"data": nil,
		})
		return
	}
	// 过滤文件类型
	ext := path.Ext(file.Filename)
	if !utils.ContainsValue(FileExt, ext) {
		ctx.JSON(http.StatusPreconditionFailed, gin.H{
			"code": http.StatusPreconditionFailed,
			"msg":  "只支持[.html]的文件上传",
			"data": nil,
		})
		return
	}

	// 创建文件路径
	savePath, err := mkDirForUpload()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	// 给文件起一个唯一名称
	fileName := utils.MakeKey(6) + ext
	filePath := ""
	// 保存文件
	filePath = path.Join(savePath.Html, fileName)
	err = ctx.SaveUploadedFile(file, filePath)
	if err != nil {
		log.Error.Println("无法保存", err.Error())
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  "服务器内部错误！",
			"data": nil,
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "上传成功",
		"data": fileName,
	})
}

func image(ctx *gin.Context) {
	file, err := ctx.FormFile("file")
	if err != nil {
		log.Error.Println(err)
		ctx.JSON(http.StatusPreconditionFailed, gin.H{
			"code": http.StatusPreconditionFailed,
			"msg":  "获取文件出错!",
			"data": nil,
		})
		return
	}
	// 过滤文件类型
	ext := path.Ext(file.Filename)
	if !utils.ContainsValue(ImageExt, ext) {
		ctx.JSON(http.StatusPreconditionFailed, gin.H{
			"code": http.StatusPreconditionFailed,
			"msg":  "只支持[.png][.jpg][.jpeg]的格式的图片上传",
			"data": nil,
		})
		return
	}


	// 创建文件路径
	savePath, err := mkDirForUpload()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	// 给文件起一个唯一名称
	fileName := utils.MakeKey(6) + ext
	filePath := ""
	// 保存文件
	filePath = path.Join(savePath.Image, fileName)
	err = ctx.SaveUploadedFile(file, filePath)
	if err != nil {
		log.Error.Println("无法保", err.Error())
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  "服务器内部错误！",
			"data": nil,
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "上传成功",
		"data": fileName,
	})
}
